package com.oak.broke.model.vip.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oak.broke.constant.CommonConstant;
import com.oak.broke.model.vip.service.ITsDmService;
import com.oak.broke.utils.RedisUtil;
import com.oak.broke.model.vip.dao.TsDmDao;
import com.oak.broke.model.vip.entity.TsDmEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tanghan
 * @Description ts_dm serviceImpl
 * @date 2023/04/13/ 10:48:00
 */
@Service
public class TsDmServiceImpl extends ServiceImpl<TsDmDao, TsDmEntity> implements ITsDmService {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public String getTsdmValByKindAndCode(String kind, String code) {
        String key = CommonConstant.REDIS_KEY_TS_DM_PREFIX + kind;
        if (!redisUtil.hasKey(key)) {
            List<TsDmEntity> tsdmList = baseMapper.listTsDmByKind(kind);
            redisUtil.setString(key, JSONObject.toJSONString(tsdmList), CommonConstant.REDIS_TS_DM_EXPIRE_TIME);
        }
        List<TsDmEntity> list = redisUtil.getList(key, TsDmEntity.class);
        Map<String, TsDmEntity> tsdmMap = list.stream().collect(Collectors.toMap(TsDmEntity::getCode, e -> e));
        if (tsdmMap.containsKey(code)) {
            return tsdmMap.get(code).getMc();
        }
        TsDmEntity tsDm = baseMapper.getTsDmByKindAndCode(kind, code);
        // ts_dm不存在，缓存空数据
        if (tsDm == null) {
            tsDm = new TsDmEntity();
            tsDm.setKind(kind);
            tsDm.setCode(code);
            tsDm.setMc("");
        }
        list.add(tsDm);
        redisUtil.setString(key, JSONObject.toJSONString(list), CommonConstant.REDIS_TS_DM_EXPIRE_TIME);
        return tsDm.getMc();
    }

    @Override
    public List<TsDmEntity> listTsDm(String kind) {
        String key = CommonConstant.REDIS_KEY_TS_DM_PREFIX + kind;
        if (!redisUtil.hasKey(key)) {
            List<TsDmEntity> tsdmList = baseMapper.listTsDmByKind(kind);
            redisUtil.setString(key, JSONObject.toJSONString(tsdmList), CommonConstant.REDIS_TS_DM_EXPIRE_TIME);
        }
        return redisUtil.getList(key, TsDmEntity.class);
    }
}
